const db = require('../db/index')

const path = require('path')


// 引入配置的对象
const config = require('../config')

// 查询文章列表
exports.getList = function(req, res) {
    console.log(req.query);
    // pagenum=1&pagesize=2&cate_id=&state=
    let { pagenum, pagesize, cate_id, state } = req.query

    pagesize = parseInt(pagesize)
    let recordNum = (parseInt(pagenum) - 1) * pagesize

    const sql = 'select a.*, c.name cate_name from ev_articles a, ev_article_cate c where a.cate_id=c.id    order by a.id  limit ?, ?'
    db.query(sql, [recordNum, pagesize], function(err, rows) {
        if (err) return res.cc(err)

        const data = rows

        const sql2 = 'select count(*) as num from ev_articles'
        db.query(sql2, function(err, rows) {
            if (err) return res.cc(err)

            res.send({
                status: 0,
                message: 'query ok',
                data,
                total: rows[0].num,
            })

        })


    })
}

// 添加 文章 
exports.addArticle = function(req, res) {
    console.log(req.file);
    console.log('--------------------');
    console.log(req.body);
    if (!req.file || req.file.fieldname !== 'cover_img')
        return res.cc('cover_img 是必须输入 ！')

    const article_info = {
        ...req.body,
        cover_img: path.join('/uploads/', req.file.filename),
        pub_date: new Date(),
        author_id: req.user.id
    }

    const sql = 'insert into ev_articles set ? '
    db.query(sql, article_info, function(err, result) {
        if (err) return res.cc(err)

        if (result.affectedRows !== 1) return res.cc('insert failed')

        res.cc('发布文章成功 ！', 0)
    })
}